package cn.ynu.cmrs.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import cn.ynu.cmrs.AppConstant;
import cn.ynu.cmrs.R;
import cn.ynu.cmrs.adapter.CourseAdapter;
import cn.ynu.cmrs.asyncTask.GetInfosTask;
import cn.ynu.cmrs.model.CollegeInfoItem;
import cn.ynu.cmrs.model.Course;
import cn.ynu.cmrs.model.CourseInfoItem;
import cn.ynu.cmrs.utils.JsonParse;
import cn.ynu.cmrs.utils.WebInterface;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.Fragment.SavedState;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public final class CourseFragment extends Fragment implements
		OnItemClickListener {

	private static final String KEY_CONTENT = "CourseFragment:CollegeInfoItem";
	/**
	 * CollegeInfoItem，用于保存当前Fragment对应的学院信息
	 */
	private CollegeInfoItem collegeInfoItem;
	/**
	 * Flag indicates whether the user had clicked "see more"
	 */
	private boolean getMoreFlag = false;
	/**
	 * The pages of course has displayed
	 */
	private int nowpage = 1;
	/**
	 * The amount of courses
	 */
	private int totalItemsCount = 0;
	/**
	 * The amount of courses has got
	 */
	private int existingItemsCount = 0;
	/**
	 * Retries of request excellent course information
	 */
	private static int retryCount = 0;
	private ArrayList<CourseInfoItem> courseList;
	ListView mListView;
	CourseAdapter adapter;

	public static CourseFragment newInstance(CollegeInfoItem item) {
		CourseFragment fragment = new CourseFragment();
		fragment.collegeInfoItem = item;
		return fragment;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (savedInstanceState != null
				&& savedInstanceState.getSerializable(KEY_CONTENT) != null) {
			collegeInfoItem = (CollegeInfoItem) (savedInstanceState
					.getSerializable(KEY_CONTENT));
		}
		View v = null;
		v = inflater.inflate(R.layout.course_list_viewpager, container, false);
		mListView = (ListView) v.findViewById(R.id.courseList);
		if (courseList == null) {
			courseList = new ArrayList<CourseInfoItem>();
			nowpage = 1;
			totalItemsCount = 0;
			existingItemsCount = 0;
			String keyword = collegeInfoItem.getName();
			new SearchCoursesByCollTask(this.getActivity(),
					R.string.fail_general, null).execute(keyword);
		}
		adapter = new CourseAdapter(this.getActivity(), courseList, mListView);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		return v;
	}
	
	@Override
	public void setInitialSavedState(SavedState state) {
		// TODO Auto-generated method stub
		super.setInitialSavedState(state);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable(KEY_CONTENT, collegeInfoItem);
	}

	/**
	 * AsyncTask class, search courses by school name
	 * 
	 * @author Yasha
	 * 
	 */
	private class SearchCoursesByCollTask extends GetInfosTask<String, Course> {

		private String keyword;

		public SearchCoursesByCollTask(Activity mActivity, int mFailMsg,
				View mView) {
			super(mActivity, mFailMsg, mView);
		}

		@Override
		protected Course doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			keyword = arg0[0];
			Map<String, String> param = new HashMap<String, String>();
			param.clear();
			param.put("interface", "getcourse");
			param.put("by", "college");
			param.put("addition", arg0[0]);
			param.put(
					"start",
					String.valueOf((nowpage - 1)
							* AppConstant.MostUsedConstant.pageSize + 1));
			param.put("amount",
					String.valueOf(AppConstant.MostUsedConstant.pageSize));
			String result = WebInterface.webInterface(param);
			Log.i("searchCourses", result);
			Course courses;
			try {
				courses = JsonParse.getCourse(result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				courses = new Course(null, null, new String[] { "8086",
						mActivity.getString(R.string.inner_error_json) });
			}
			return courses;
		}

		@Override
		protected void onPostExecute(Course result) {
			// TODO Auto-generated method stub
			String[] status = result.getStatus();
			if (status[0].equals("0")) {
				retryCount = 0;
				if (result.getItems() != null)
					doStuffWithResult(result);
			} else {
				if (retryCount < 3) {
					new SearchCoursesByCollTask(mActivity,
							R.string.fail_general, null).execute(keyword);
					retryCount++;
				} else {
					failMsg(status[1]);
				}
			}
		}

		@Override
		protected void doStuffWithResult(Course result) {
			// TODO Auto-generated method stub
			if (nowpage == 1) {
				totalItemsCount = result.getHead().getTotalItems();
				existingItemsCount = result.getHead().getAmount();
				courseList = (ArrayList<CourseInfoItem>) result.getItems();
				((CourseAdapter) mListView.getAdapter())
						.addMoreData(new ArrayList<CourseInfoItem>(result
								.getItems()));
			} else {
				existingItemsCount += result.getHead().getAmount();
				courseList
						.addAll((ArrayList<CourseInfoItem>) result.getItems());
				((CourseAdapter) mListView.getAdapter())
						.addMoreData(new ArrayList<CourseInfoItem>(result
								.getItems()));
			}
			nowpage++;
			getMoreFlag = false;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		if (arg3 == -1) {
			if (!getMoreFlag) {
				if (existingItemsCount >= totalItemsCount) {
					Toast.makeText(this.getActivity(), R.string.no_moreitems,
							Toast.LENGTH_LONG).show();
				} else {
					getMoreFlag = true;
					String keyword = collegeInfoItem.getName();
					new SearchCoursesByCollTask(this.getActivity(),
							R.string.fail_general, null).execute(keyword);
				}
			}
		}
	}

}
